<?php

namespace App\Api\Http\Middleware;

use App\Repositories\User\UserTokenRepositoryInterface;
use Closure;

class ApiTokenCheck
{
    /**
     * @var UserTokenRepositoryInterface
     */
    protected $user_token_repository;

    public function __construct(UserTokenRepositoryInterface $user_token_repository)
    {
        $this->user_token_repository = $user_token_repository;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        if (!$token) {
            $token = $request->get('token');
        }

        $user_id = 0;
        if ($token) {
            $user_id = $this->user_token_repository->getUserIdByToken($token);
        }

        access()->setUserId($user_id);
        if (access()->check()) {
            access()->setToken($token);
        }

        return $next($request);
    }
}
